<template>
  <div class="CommonPictureUpload">
    <div class="list">
      <div class="item" v-for="(item, index) in currentValue" :key="item">
        <div class="name" @click="handleViewFile(item)">{{ item.name }}</div>
        <van-icon name="clear" color="#D1272F" @click="handleClearPhoto(index)" v-if="!isView" />
      </div>
    </div>
    <div class="btn" @click="handleChoosePhoto" v-show="!isView" v-if="(isArray && currentValue.length < length) || (!isArray && currentValue.length < 1)">
      从微信记录中选取文件
    </div>
  </div>
</template>

<script>
import api from '@/api'
import wxp from '@/utils/wxp'
import { generateImgUrl } from '@/utils'
import isEqual from 'lodash.isequal'
import cloneDeep from 'lodash.clonedeep'

export default {
  props: {
    value: {
      type: [String, Array],
      required: true,
    },
    isOnlyCamera: {
      type: Boolean,
    },
    data: {
      type: Object,
      default () {
        return {}
      },
    },
    api: {
      type: Function,
      default () {
        return api.uploadFile
      },
    },
    length: {
      type: Number,
      default: 9999,
    },
    beforeUpload: {
      type: Function,
      default () {
        return (filePath) => filePath
      },
    },
    isView: {
      type: Boolean,
    },
  },
  data () {
    return {
      generateImgUrl,
      currentValue: [],
    }
  },
  computed: {
    isArray () {
      return Array.isArray(this.value)
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler (newVal, oldVal) {
        if (!isEqual(this.value, this.currentValue)) {
          this.currentValue = cloneDeep(this.value)
        }
      },
    },
  },
  methods: {
    async handleChoosePhoto () {
      const { tempFiles } = await wxp.chooseMessageFile({
        count: 1,
        type: 'all',
      })
      const file = await this.beforeUpload(tempFiles[0])
      const { result } = await this.api(Object.assign({}, { filePath: file.path, name: 'file' }, this.data))
      if (!this.isArray) {
        this.currentValue = [result]
        this.$emit('input', result)
      } else {
        this.currentValue.push(result)
        this.$emit('input', cloneDeep(this.currentValue))
      }
    },
    handleViewPhoto (item) {
      wx.previewImage({
        urls: [generateImgUrl(item)],
      })
    },
    handleClearPhoto (index) {
      if (!this.isArray) {
        this.currentValue = []
        this.$emit('input', '')
      } else {
        this.currentValue.splice(index, 1)
        this.$emit('input', cloneDeep(this.currentValue))
      }
    },
    handleViewFile (file) {
      wx.showLoading()
      wx.downloadFile({
        url: generateImgUrl(file.showPath),
        success ({ tempFilePath }) {
          wx.hideLoading()
          wx.openDocument({
            filePath: tempFilePath,
            showMenu: true,
            fileType: file.name.split('.')[1],
            fail (e) {
              console.log('openDocument fail', e)
              uni.showModal({
                title: '错误',
                showCancel: false,
              })
            },
          })
        },
        fail () {
          wx.hideLoading()
          uni.showModal({
            title: '错误',
            showCancel: false,
          })
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped> @import "~css/var.scss";

.CommonPictureUpload {
	margin-top: 20px;

	.list {
		.item {
			display: flex;
			align-items: center;
			margin-top: 10px;

			.name {
				display: flex;
				overflow: hidden;
				box-sizing: border-box;
				width: 90%;
				margin: 0 10px 0 0;
				padding: 3px 7px;
				border: 1px solid #d9d9d9;
				border-radius: 4px;
				line-height: 20px;
				text-overflow: ellipsis;
				font-size: $fz-l;
				color: rgba(0, 0, 0, .65);
				background: #fafafa;
				white-space: nowrap;
			}
		}
	}

	.btn {
		width: 330rpx;
		margin: 15px 0;
		border-radius: 5px;
		line-height: 30px;
		text-align: center;
		font-size: $fz-m;
		color: #fff;
		background: #d1272f;

		&.hover {
			opacity: .8;
		}
	}
}
</style>
